<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/JQ.js"></script>
</head>
<body>
昵称：<input style="width: 40px" id="nam" type="text" onchange="nam()">
<input value="发送" type="button" onclick="aa()">
<input id="info" type="text">

<br/>
<div id="a" style="width: 300px;height: 150px;overflow: auto;display: inline-block">
    <p id="aa"></p>
</div>
</body>
<script>
    console.log(origin)
    const myUrl = origin.split("http");
    const soc = "ws" + myUrl[1] + "/socket/chat";
    const socket = new WebSocket(soc);

    function nam() {
        const val = $("#nam").val();
        if (val !== "") {
            $("#nam").attr("disabled", "disabled")
        } else {
            return;
        }
    }

    socket.onopen = function (event) {
        console.log("连接服务端成功！");
        socket.send("");
        console.log(event);
    };

    // 服务端关闭连接后触发
    socket.onclose = function (event) {
        console.log("服务器关闭连接！");
        console.log(event);
    };

    // 服务端发送数据，接收到数据后
    socket.onmessage = function (event) {
        console.log("接收到信息！");
        console.log(event.data);
        $("#aa").after(`<p>${event.data}</p>`)
    };

    // 发生异常时触发，比如消息无法发送等
    socket.onerror = function (event) {
        console.log("发生错误！");
        console.log(event);
    };


    // $('#exit').click(function(){
    //     // 关闭连接
    //     socket.close([code,reason]);
    //     // code 关闭连接的状态码，默认1005
    //     // reason 关闭连接的原因字符串
    // });

    function aa() {
        // 向服务端发送数据
        const val = $("#nam").val();
        if (val === "") {
            alert("昵称为空")
            return;
        }
        const data = $("#info").val();
        if (data === "") {
            alert("消息为空")
            return;
        }
        socket.send(val + ": " + data);
        $("#info").val("");

    }
</script>
</html>